// This file is not belongs to this project. Only for automatically booking a railway ticket when I was in China. 
// Non-Chinese cannot understand that situation. How difficult to buy a railway ticket at chinese new year :(

// 获得iframe
var cw = $("#main")[0].contentWindow;

// 只检查第一趟车的软卧是否有票，如果有票，并且预定按钮可用，则进入预定页面
var autoexec = function() {
    var btnSearch = cw.$(".search_u");
    if (btnSearch[0]) btnSearch.click();
    else console.log("查询按钮还在禁用状态");
    var cellsOfFirstRow = cw.$("tr.ev_light").first().children();
    var infoRW = cellsOfFirstRow[9].innerText;
    var btnBook = cellsOfFirstRow.find(".btn130_2");            
    if (infoRW == "无" ) console.log("无票");
    else if (infoRW == "*") console.log("还没开始放票 ...");
    else if (btnBook[0]) {
        btnBook.click();
        clearInterval(autohandler);
		autoBook();              
    }
}

function autoBook() {
	if (!cw.$ || cw.$("#showPassengerFilter").length == 0) {
		setTimeout(autoBook, 100);
	} else {
		// 进入预定页面后，点击复选框，选中所有乘客
		cw.$("#showPassengerFilter").find("input[type=checkbox]").each(function(){
		  $(this).click();
		});
		// 验证码输入框获得焦点
		cw.$("input#rand")[0].focus();
		// 填写完验证码后自动提交
		cw.$("input#rand").keyup(function(){
		  if($(this).val().length==4) {
		    cw.$(".tj_btn").find("button").last().click();
		    // 点击确定按钮
		    //$(".ui-dialog-buttonpane").find("button").last().click();
		  }
		});
    }		
}
     
        
// 注入按钮
var btnStart = $("<input type='button' value=' 开始刷票 ' style='height:35px;background:lightgreen;'>");
var btnStop = $("<input type='button' value=' 停止刷票 ' style='height:35px;background:lightsalmon'>")
$("body").before(btnStop).before(btnStart);

// 绑定按钮点击事件, 每隔5秒半自动查票一次
btnStart.bind("click", function() {
  autohandler = setInterval(autoexec, 5500); 
  console.log("Auto query started...");
});

// 绑定按钮点击事件，停止自动查票
btnStop.bind("click", function() {
  clearInterval(autohandler); 
  console.log("Auto query stoped.");
});